import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
    Box,
    Container,
    Paper,
    Typography,
    Button,
    TextField,
    Grid,
    CircularProgress,
    Snackbar,
    Alert,
    Divider,
    IconButton,
    Card,
    CardContent,
    FormControlLabel,
    Switch,
    Tabs,
    Tab,
    InputAdornment,
} from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import LinkIcon from '@mui/icons-material/Link';
import QrCodeIcon from '@mui/icons-material/QrCode';
import EmailIcon from '@mui/icons-material/Email';
import WhatsAppIcon from '@mui/icons-material/WhatsApp';
import FacebookIcon from '@mui/icons-material/Facebook';
import TwitterIcon from '@mui/icons-material/Twitter';
import LinkedInIcon from '@mui/icons-material/LinkedIn';
import { useAuth } from '../contexts/AuthContext';

const ResumeShare = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const { isAuthenticated } = useAuth();
    const [loading, setLoading] = useState(true);
    const [resume, setResume] = useState(null);
    const [activeTab, setActiveTab] = useState(0);
    const [shareSettings, setShareSettings] = useState({
        isPublic: true,
        requirePassword: false,
        password: '',
        expiryDate: '',
    });
    const [snackbar, setSnackbar] = useState({
        open: false,
        message: '',
        severity: 'success'
    });

    // 生成分享链接
    const shareUrl = `https://resumeshare.com/share/${id}`;

    // 生成二维码链接 (在实际应用中，这应该是一个API调用)
    const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(shareUrl)}`;

    // 加载简历数据
    useEffect(() => {
        const loadResumeData = async () => {
            try {
                // 在实际应用中，这应该是一个API调用
                setTimeout(() => {
                    const mockResume = {
                        id: id,
                        title: '软件工程师简历',
                        isPublic: true,
                        shareSettings: {
                            requirePassword: false,
                            password: '',
                            expiryDate: '',
                        }
                    };

                    setResume(mockResume);
                    setShareSettings({
                        isPublic: mockResume.isPublic,
                        requirePassword: mockResume.shareSettings.requirePassword,
                        password: mockResume.shareSettings.password,
                        expiryDate: mockResume.shareSettings.expiryDate,
                    });
                    setLoading(false);
                }, 1000);
            } catch (error) {
                console.error('加载简历数据失败:', error);
                setLoading(false);
            }
        };

        loadResumeData();
    }, [id]);

    // 处理标签页切换
    const handleTabChange = (event, newValue) => {
        setActiveTab(newValue);
    };

    // 处理分享设置变更
    const handleSettingChange = (event) => {
        const { name, value, checked, type } = event.target;
        setShareSettings({
            ...shareSettings,
            [name]: type === 'checkbox' ? checked : value,
        });
    };

    // 保存分享设置
    const handleSaveSettings = async () => {
        try {
            // 在实际应用中，这应该是一个API调用
            // 这里我们只是模拟保存过程
            await new Promise(resolve => setTimeout(resolve, 1000));

            setSnackbar({
                open: true,
                message: '分享设置已保存',
                severity: 'success'
            });
        } catch (error) {
            console.error('保存分享设置失败:', error);
            setSnackbar({
                open: true,
                message: '保存分享设置失败',
                severity: 'error'
            });
        }
    };

    // 复制链接到剪贴板
    const handleCopyLink = () => {
        navigator.clipboard.writeText(shareUrl).then(() => {
            setSnackbar({
                open: true,
                message: '链接已复制到剪贴板',
                severity: 'success'
            });
        }, (err) => {
            console.error('无法复制链接:', err);
            setSnackbar({
                open: true,
                message: '复制链接失败',
                severity: 'error'
            });
        });
    };

    // 返回上一页
    const handleBack = () => {
        navigate(-1);
    };

    // 关闭提示框
    const handleCloseSnackbar = () => {
        setSnackbar({ ...snackbar, open: false });
    };

    // 如果正在加载，显示加载指示器
    if (loading) {
        return (
            <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '80vh' }}>
                <CircularProgress />
            </Box>
        );
    }

    // 如果简历不存在
    if (!resume) {
        return (
            <Container maxWidth="md" sx={{ mt: 4, mb: 8, textAlign: 'center' }}>
                <Typography variant="h4" gutterBottom>
                    简历不存在或已被删除
                </Typography>
                <Button variant="contained" onClick={() => navigate('/dashboard')} sx={{ mt: 2 }}>
                    返回仪表盘
                </Button>
            </Container>
        );
    }

    return (
        <Container maxWidth="md" sx={{ mt: 4, mb: 8 }}>
            {/* 页面头部 */}
            <Box sx={{ mb: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <IconButton onClick={handleBack} sx={{ mr: 2 }}>
                        <ArrowBackIcon />
                    </IconButton>
                    <Typography variant="h5" component="h1">
                        分享 "{resume.title}"
                    </Typography>
                </Box>
            </Box>

            {/* 分享选项卡 */}
            <Paper sx={{ mb: 4 }}>
                <Tabs
                    value={activeTab}
                    onChange={handleTabChange}
                    variant="fullWidth"
                    indicatorColor="primary"
                    textColor="primary"
                >
                    <Tab label="分享链接" icon={<LinkIcon />} iconPosition="start" />
                    <Tab label="二维码" icon={<QrCodeIcon />} iconPosition="start" />
                    <Tab label="社交媒体" icon={<FacebookIcon />} iconPosition="start" />
                    {isAuthenticated && <Tab label="分享设置" icon={<ContentCopyIcon />} iconPosition="start" />}
                </Tabs>

                {/* 分享链接 */}
                {activeTab === 0 && (
                    <Box sx={{ p: 3 }}>
                        <Typography variant="h6" gutterBottom>
                            通过链接分享
                        </Typography>
                        <Typography variant="body2" color="text.secondary" paragraph>
                            复制以下链接并分享给招聘方或朋友
                        </Typography>

                        <TextField
                            fullWidth
                            value={shareUrl}
                            variant="outlined"
                            InputProps={{
                                readOnly: true,
                                endAdornment: (
                                    <InputAdornment position="end">
                                        <Button
                                            variant="contained"
                                            onClick={handleCopyLink}
                                            startIcon={<ContentCopyIcon />}
                                        >
                                            复制
                                        </Button>
                                    </InputAdornment>
                                ),
                            }}
                            sx={{ mb: 3 }}
                        />

                        <Typography variant="body2" color="text.secondary">
                            任何拥有此链接的人都可以查看您的简历
                            {shareSettings.requirePassword && " (需要密码)"}
                        </Typography>
                    </Box>
                )}

                {/* 二维码 */}
                {activeTab === 1 && (
                    <Box sx={{ p: 3, textAlign: 'center' }}>
                        <Typography variant="h6" gutterBottom>
                            通过二维码分享
                        </Typography>
                        <Typography variant="body2" color="text.secondary" paragraph>
                            扫描二维码即可查看简历
                        </Typography>

                        <Box sx={{ my: 3 }}>
                            <img
                                src={qrCodeUrl}
                                alt="简历分享二维码"
                                style={{
                                    width: '200px',
                                    height: '200px',
                                    border: '1px solid #eee',
                                    borderRadius: '4px',
                                }}
                            />
                        </Box>

                        <Button
                            variant="outlined"
                            onClick={() => {
                                // 在实际应用中，这应该是一个下载功能
                                window.open(qrCodeUrl, '_blank');
                            }}
                        >
                            下载二维码
                        </Button>
                    </Box>
                )}

                {/* 社交媒体 */}
                {activeTab === 2 && (
                    <Box sx={{ p: 3 }}>
                        <Typography variant="h6" gutterBottom>
                            通过社交媒体分享
                        </Typography>
                        <Typography variant="body2" color="text.secondary" paragraph>
                            选择一个平台分享您的简历
                        </Typography>

                        <Grid container spacing={2} sx={{ mt: 2 }}>
                            <Grid item xs={6} sm={3}>
                                <Button
                                    fullWidth
                                    variant="outlined"
                                    startIcon={<EmailIcon />}
                                    href={`mailto:?subject=我的简历&body=查看我的简历：${shareUrl}`}
                                    sx={{ justifyContent: 'flex-start', py: 1.5 }}
                                >
                                    邮件
                                </Button>
                            </Grid>
                            <Grid item xs={6} sm={3}>
                                <Button
                                    fullWidth
                                    variant="outlined"
                                    startIcon={<WhatsAppIcon />}
                                    href={`https://api.whatsapp.com/send?text=${encodeURIComponent(`查看我的简历：${shareUrl}`)}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    sx={{ justifyContent: 'flex-start', py: 1.5 }}
                                >
                                    WhatsApp
                                </Button>
                            </Grid>
                            <Grid item xs={6} sm={3}>
                                <Button
                                    fullWidth
                                    variant="outlined"
                                    startIcon={<LinkedInIcon />}
                                    href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl)}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    sx={{ justifyContent: 'flex-start', py: 1.5 }}
                                >
                                    LinkedIn
                                </Button>
                            </Grid>
                            <Grid item xs={6} sm={3}>
                                <Button
                                    fullWidth
                                    variant="outlined"
                                    startIcon={<TwitterIcon />}
                                    href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(`查看我的简历：${shareUrl}`)}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    sx={{ justifyContent: 'flex-start', py: 1.5 }}
                                >
                                    Twitter
                                </Button>
                            </Grid>
                        </Grid>
                    </Box>
                )}

                {/* 分享设置 (仅登录用户可见) */}
                {activeTab === 3 && isAuthenticated && (
                    <Box sx={{ p: 3 }}>
                        <Typography variant="h6" gutterBottom>
                            分享设置
                        </Typography>
                        <Typography variant="body2" color="text.secondary" paragraph>
                            自定义您的简历分享选项
                        </Typography>

                        <Card variant="outlined" sx={{ mb: 3 }}>
                            <CardContent>
                                <FormControlLabel
                                    control={
                                        <Switch
                                            checked={shareSettings.isPublic}
                                            onChange={handleSettingChange}
                                            name="isPublic"
                                        />
                                    }
                                    label="公开简历"
                                />
                                <Typography variant="body2" color="text.secondary" sx={{ ml: 4, mb: 2 }}>
                                    允许任何人通过链接查看您的简历
                                </Typography>

                                <Divider sx={{ my: 2 }} />

                                <FormControlLabel
                                    control={
                                        <Switch
                                            checked={shareSettings.requirePassword}
                                            onChange={handleSettingChange}
                                            name="requirePassword"
                                            disabled={!shareSettings.isPublic}
                                        />
                                    }
                                    label="需要密码"
                                />

                                {shareSettings.requirePassword && (
                                    <TextField
                                        fullWidth
                                        label="设置密码"
                                        name="password"
                                        type="password"
                                        value={shareSettings.password}
                                        onChange={handleSettingChange}
                                        margin="normal"
                                        disabled={!shareSettings.isPublic}
                                    />
                                )}

                                <Divider sx={{ my: 2 }} />

                                <Typography variant="subtitle2" gutterBottom>
                                    设置过期时间
                                </Typography>
                                <TextField
                                    fullWidth
                                    label="过期日期"
                                    name="expiryDate"
                                    type="date"
                                    value={shareSettings.expiryDate}
                                    onChange={handleSettingChange}
                                    margin="normal"
                                    InputLabelProps={{
                                        shrink: true,
                                    }}
                                    helperText="如果不设置，链接将永久有效"
                                    disabled={!shareSettings.isPublic}
                                />
                            </CardContent>
                        </Card>

                        <Button
                            variant="contained"
                            onClick={handleSaveSettings}
                            fullWidth
                        >
                            保存设置
                        </Button>
                    </Box>
                )}
            </Paper>

            {/* 预览提示 */}
            <Box sx={{ textAlign: 'center' }}>
                <Button
                    variant="outlined"
                    onClick={() => navigate(`/resume/${id}`)}
                >
                    预览简历
                </Button>
            </Box>

            {/* 提示框 */}
            <Snackbar
                open={snackbar.open}
                autoHideDuration={6000}
                onClose={handleCloseSnackbar}
                anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            >
                <Alert
                    onClose={handleCloseSnackbar}
                    severity={snackbar.severity}
                    sx={{ width: '100%' }}
                >
                    {snackbar.message}
                </Alert>
            </Snackbar>
        </Container>
    );
};

export default ResumeShare; 